/**
 * RBAC权限工具类
 * 简化的前端权限辅助功能，复杂权限计算由后端处理
 */

import type { User, Role, Permission, Department, Team } from '../../../types/rbac';

/**
 * 前端权限工具类
 * 提供基础的权限辅助功能和常量定义
 */
export class RbacUtils {
  
  /**
   * 适配auth store中的用户数据结构
   */
  static adaptAuthUser(authUser: any): User {
    return {
      ...authUser,
      account: authUser.username || authUser.account,
      status: 1, // 默认激活状态
      createTime: authUser.createTime || new Date().toISOString(),
      roles: authUser.roles?.map((roleCode: string) => ({
        id: roleCode,
        code: roleCode,
        name: roleCode,
        permissions: [],
        status: 'active' as const,
        createTime: new Date().toISOString(),
        updateTime: new Date().toISOString(),
        createdBy: 'system'
      })) || [],
      permissions: authUser.permissions?.map((permCode: string) => ({
        id: permCode,
        code: permCode,
        name: permCode,
        category: permCode.split(':')[0] || 'system',
        resource: permCode.split(':')[0] || 'system',
        action: permCode.split(':')[1] || 'read',
        createTime: new Date().toISOString(),
        updateTime: new Date().toISOString()
      })) || []
    };
  }
  
  /**
   * 检查用户是否拥有指定权限（适配版本）
   */
  static hasPermissionAdapted(authUser: any, permissionCode: string): boolean {
    if (!authUser) {
      return false;
    }
    
    // 如果permissions是字符串数组，直接检查
    if (Array.isArray(authUser.permissions) && typeof authUser.permissions[0] === 'string') {
      // 检查是否有超级管理员权限
      if (authUser.permissions.includes('*') || authUser.permissions.includes('admin:*')) {
        return true;
      }
      
      // 检查精确匹配的权限
      if (authUser.permissions.includes(permissionCode)) {
        return true;
      }
      
      // 检查通配符权限
      const parts = permissionCode.split(':');
      for (let i = parts.length - 1; i > 0; i--) {
        const wildcardPermission = parts.slice(0, i).join(':') + ':*';
        if (authUser.permissions.includes(wildcardPermission)) {
          return true;
        }
      }
      
      return false;
    }
    
    // 如果是完整的User对象，使用原方法
    return this.hasBasicPermission(this.adaptAuthUser(authUser), permissionCode);
  }
  
  /**
   * 检查用户是否拥有指定角色（适配版本）
   */
  static hasRoleAdapted(authUser: any, roleCode: string): boolean {
    if (!authUser) {
      return false;
    }
    
    // 如果roles是字符串数组，直接检查
    if (Array.isArray(authUser.roles) && typeof authUser.roles[0] === 'string') {
      return authUser.roles.includes(roleCode);
    }
    
    // 如果是完整的User对象，使用原方法
    return this.hasBasicRole(this.adaptAuthUser(authUser), roleCode);
  }
  
  /**
   * 检查用户是否拥有指定权限（简化版本）
   * 注意：这只是前端辅助功能，真实权限验证应该通过API进行
   */
  static hasBasicPermission(user: User, permissionCode: string): boolean {
    if (!user || !user.permissions) {
      return false;
    }
    
    // 检查是否有超级管理员权限
    const permissionCodes = user.permissions.map(p => p.code);
    if (permissionCodes.includes('*') || permissionCodes.includes('admin:*')) {
      return true;
    }
    
    // 检查精确匹配的权限
    if (permissionCodes.includes(permissionCode)) {
      return true;
    }
    
    // 检查通配符权限
    const parts = permissionCode.split(':');
    for (let i = parts.length - 1; i > 0; i--) {
      const wildcardPermission = parts.slice(0, i).join(':') + ':*';
      if (permissionCodes.includes(wildcardPermission)) {
        return true;
      }
    }
    
    return false;
  }
  
  /**
   * 检查用户是否拥有指定角色（简化版本）
   */
  static hasBasicRole(user: User, roleCode: string): boolean {
    if (!user || !user.roles) {
      return false;
    }
    
    return user.roles.some(role => role.code === roleCode);
  }
  
  /**
   * 检查用户是否拥有任意一个指定的权限
   */
  static hasAnyPermission(user: User, permissionCodes: string[]): boolean {
    return permissionCodes.some(code => this.hasBasicPermission(user, code));
  }
  
  /**
   * 检查用户是否拥有所有指定的权限
   */
  static hasAllPermissions(user: User, permissionCodes: string[]): boolean {
    return permissionCodes.every(code => this.hasBasicPermission(user, code));
  }
  
  /**
   * 检查用户是否拥有任意一个指定的角色
   */
  static hasAnyRole(user: User, roleCodes: string[]): boolean {
    return roleCodes.some(code => this.hasBasicRole(user, code));
  }
  
  /**
   * 根据ID查找部门（支持嵌套）
   */
  static findDepartmentById(
    departmentId: string,
    departments: Department[]
  ): Department | undefined {
    for (const dept of departments) {
      if (dept.id === departmentId) {
        return dept;
      }
      
      if (dept.children) {
        const found = this.findDepartmentById(departmentId, dept.children);
        if (found) {
          return found;
        }
      }
    }
    
    return undefined;
  }
  
  /**
   * 获取部门的所有子部门ID
   */
  static getDepartmentChildrenIds(
    departmentId: string,
    allDepartments: Department[]
  ): string[] {
    const department = this.findDepartmentById(departmentId, allDepartments);
    if (!department) {
      return [];
    }
    
    const childrenIds: string[] = [];
    
    const collectChildren = (dept: Department) => {
      if (dept.children) {
        dept.children.forEach(child => {
          childrenIds.push(child.id);
          collectChildren(child);
        });
      }
    };
    
    collectChildren(department);
    return childrenIds;
  }
}

// 权限常量定义
export const PERMISSION_CATEGORIES = {
  USER: 'user',
  ROLE: 'role',
  TEAM: 'team',
  PERMISSION: 'permission',
  MENU: 'menu',
  SYSTEM: 'system',
  REPORT: 'report'
} as const;

export const PERMISSION_ACTIONS = {
  READ: 'read',
  WRITE: 'write',
  UPDATE: 'update',
  DELETE: 'delete',
  EXPORT: 'export',
  IMPORT: 'import',
  ASSIGN: 'assign',
  MANAGE: 'manage'
} as const;

// 预定义权限代码
export const PREDEFINED_PERMISSION_CODES = {
  // 用户管理
  USER_READ: 'user:read',
  USER_WRITE: 'user:write',
  USER_UPDATE: 'user:update',
  USER_DELETE: 'user:delete',
  USER_EXPORT: 'user:export',
  
  // 角色管理
  ROLE_READ: 'role:read',
  ROLE_WRITE: 'role:write',
  ROLE_UPDATE: 'role:update',
  ROLE_DELETE: 'role:delete',
  ROLE_ASSIGN: 'role:assign',
  
  // 团队管理
  TEAM_READ: 'team:read',
  TEAM_WRITE: 'team:write',
  TEAM_UPDATE: 'team:update',
  TEAM_DELETE: 'team:delete',
  TEAM_MANAGE: 'team:manage',
  
  // 权限管理
  PERMISSION_READ: 'permission:read',
  PERMISSION_WRITE: 'permission:write',
  PERMISSION_UPDATE: 'permission:update',
  PERMISSION_DELETE: 'permission:delete',
  
  // 系统管理
  SYSTEM_READ: 'system:read',
  SYSTEM_WRITE: 'system:write',
  SYSTEM_LOG: 'system:log',
  SYSTEM_MONITOR: 'system:monitor',
} as const;

export type PermissionCode = typeof PREDEFINED_PERMISSION_CODES[keyof typeof PREDEFINED_PERMISSION_CODES];